import React from 'react';
import images from '@/images';
import ajax from 'decorate/ajax';
import Stars from 'components/Stars';
import NoData from 'components/NoData';
import Calendar1 from 'business/calendar';
const calendar = ['日', '一', '二', '三', '四', '五', '六'];
class CalendarBox extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            dates: [],
            selectedValue: props.value || XUE.formatDate(new Date(), 'yyyy-MM-dd'),
        };
        this.myRef = React.createRef();
    }

    componentDidMount() {
        const now = new Date();
        const dates = [];
        for (let i = 0; i < 49; i++) {
            const target = XUE.addDate(now, i - 25);
            dates.push({
                dt: target,
                month: target.getMonth(),
                week: target.getDay(),
                date: target.getDate()
            });
        }
        this.setState({
            dates
        }, () => {
            const wrapperWidth = parseInt(getComputedStyle(this.myRef.current, null).width);
            const childWidth = parseInt(getComputedStyle(this.myRef.current.childNodes[0], null).width);
            const nn = Math.floor(wrapperWidth / childWidth) / 2;
            const scrollLeft = childWidth * 25 + (nn * childWidth - 0.5 * wrapperWidth);
            this.myRef.current.scrollLeft = scrollLeft;
        });
    }

    onScroll = (e) => {
        const length = this.myRef.current.childNodes.length;
        const childWidth = parseInt(getComputedStyle(this.myRef.current.childNodes[0], null).width);
        if (this.myRef.current.scrollLeft > childWidth * (length - 8)) {
            const lastDate = this.state.dates[this.state.dates.length - 1];
            for (let i = 1; i < 16; i++) {
                const target = XUE.addDate(lastDate.dt, i);
                const date = {
                    dt: target,
                    month: target.getMonth(),
                    week: target.getDay(),
                    date: target.getDate()
                };
                this.state.dates.push(date);
            }
            this.setState({
                dates: this.state.dates
            });
        } else if (this.myRef.current.scrollLeft < 8 * childWidth) {
            const lastDate = this.state.dates[0];
            for (let i = 1; i < 16; i++) {
                const target = XUE.addDate(lastDate.dt, -i);
                const date = {
                    dt: target,
                    month: target.getMonth(),
                    week: target.getDay(),
                    date: target.getDate()
                };
                this.state.dates.unshift(date);
            }
            this.setState({
                dates: this.state.dates
            }, () => {
                this.myRef.current.scrollLeft += 15 * childWidth;
            });
        }
    }

    onClickDate = (e) => {
        const { calendar } = e.currentTarget.dataset;
        const { onCalendar } = this.props;
        this.setState({
            selectedValue: calendar
        }, () => {
            onCalendar && onCalendar(calendar);
        });
    }

    render() {
        const { dates = [], selectedValue } = this.state;
        return (
            <div ref={this.myRef} className="calendar-box" onScrollCapture={this.onScroll}>
                {
                    dates.map((item) => {
                        return (
                            <div
                                className={`calendar-box-item ${selectedValue === XUE.formatDate(item.dt, 'yyyy-MM-dd') ? 'active' : ''}`}
                                key={XUE.formatDate(item.dt, 'yyyy-MM-dd')}
                                onClick={this.onClickDate}
                                data-calendar={XUE.formatDate(item.dt, 'yyyy-MM-dd')}
                            >
                                <span className="calendar-month">
                                    {item.dt.getDate() === 1 ? `${item.month > 9 ? item.month + 1 : `0${item.month + 1}`}月` : ''}
                                </span>
                                <p>周{calendar[item.week]}</p>
                                <p>{item.date > 9 ? item.date : `0${item.date}`}</p>
                            </div>
                        );
                    })
                }
            </div>
        );
    }
}

class CalendarItem extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        const {
            ccy = '', fluence = '', name = '', star = 1,
            actual = '-', country = '', previous = '-',
            consensus = '-', pub_time = ''
        } = this.props;
        const date = new Date(pub_time);

        return (
            <div className="calendar-item-wrapper">
                <div className="calendar-item-flag">
                    <img src={images[country]} className="calendar-item-img" />
                </div>
                <div className="calendar-item-box">
                    <div className="calendar-item-title">
                        <div className="calendar-item-info">
                            <div>{XUE.formatDate(date, 'hh:mm')}</div>
                            <div className="seize" />
                            {star <= 2 && <Stars total="5" value={star} />}
                            {star >= 3 && <Stars total="5" value={star} important />}
                        </div>
                        <div className="calendar-item-fluence">
                            {country}{name}
                        </div>
                    </div>
                    <div className="calendar-item-data">
                        <div className="calendar-data-info">前值：{previous}</div>
                        <div className="calendar-data-info">预期：{consensus}</div>
                        <div className="calendar-data-info">公布：{actual}</div>
                    </div>
                </div>
            </div>
        );
    }
}

@ajax(Calendar1.url,Calendar1.meta, Calendar1.resolve)
class Calendar extends React.Component {
    componentWillReceiveProps(nextProps, nextContext) {
        const { year, month, day } = nextProps;
        if (year !== this.props.year || month !== this.props.month || day !== this.props.day) {
            setTimeout(() => {
                this.postAjax();
            }, 0);

        }
    }

    render() {
        const { calendars = [] } = this.props;

        if (calendars.length === 0) {
            return <NoData />
        }
        return (
            <div>
                {
                    calendars.map((item) => {
                        return <CalendarItem {...item} />
                    })
                }
            </div>
        );
    }
}

export default class extends React.Component {
    constructor(props) {
        super(props);
        const now = new Date();
        this.state = {
            tabIndex: 'data',
            year: `${now.getFullYear()}`,
            month: now.getMonth() + 1 > 9 ? `${now.getMonth() + 1}` : `0${now.getMonth() + 1}`,
            day: `${now.getDate()}`
        }
    }

    onChangeTab = (e) => {
        const { index } = e.currentTarget.dataset;
        const { onChange } = this.props;
        this.setState({
            tabIndex: index
        }, () => {
            onChange && onChange(index);
        });
    }

    onCalendar = (date) => {
        const now = new Date(date);
        console.log(date);
        this.setState({
            year: `${now.getFullYear()}`,
            month: now.getMonth() + 1 > 9 ? `${now.getMonth() + 1}` : `0${now.getMonth() + 1}`,
            day: `${now.getDate()}`
        }, () => {
            console.log(this.state);
        })
    }

    render() {
        const { tabIndex, year = '', month = '', day = '' } = this.state;
        return (
            <div className="app-calendar-wrapper">
                <div className="app-calendar-date-box">
                    <CalendarBox onCalendar={this.onCalendar}/>
                </div>
                <div className="app-calendar-wrapper-content">
                    <Calendar year={year} month={month} day={day} />
                </div>
            </div>
        );
    }
}
